package routers

import (
	"net/http"
	"path"
	"strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
)

func init() {
	beego.InsertFilter("/", beego.BeforeRouter, WebServerFilter)
	beego.InsertFilter("/*", beego.BeforeRouter, WebServerFilter)

}

// 静态文件后缀
const staticFileExt = ".html|.js|.css|.png|.jpg|.jpeg|.ico|.otf|.svg"

// web 服务过滤器,实现静态文件发布
func WebServerFilter(ctx *context.Context) {
	urlPath := ctx.Request.URL.Path
	if urlPath == "" || urlPath == "/" {
		urlPath = "index.html"
	}
	ext := path.Ext(urlPath)
	index := strings.Index(staticFileExt, ext)
	if ext != "" && index >= 0 {
		http.ServeFile(ctx.ResponseWriter, ctx.Request, "static/"+urlPath)
	} else {
		if !(len(urlPath) > 4 && urlPath[0:4] == "/api") {
			//非后端api多页面路由修改
			http.ServeFile(ctx.ResponseWriter, ctx.Request, "static/"+urlPath+".html")
			//http.ServeFile(ctx.ResponseWriter, ctx.Request, "static/index.html")
		} //后端api接口路由可自行添加

	}
}
